package cn.xiaye.blog.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import cn.xiaye.blog.bean.User;
import cn.xiaye.blog.db.util.DbUtil;

public class UserDao {
	DbUtil dbUtil = DbUtil.getDefaultDatabaseUtil();

	public boolean login(String name, String password) {
		PreparedStatement ps = null;
		ps = dbUtil
				.prepareStatement("select * from login where name=? and password=?");
		ResultSet rs = null;
		boolean b = false;
		try {
			ps.setString(1, name);
			ps.setString(2, password);
			rs = ps.executeQuery();
			b = rs.next();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			dbUtil.close(ps);
			dbUtil.close(rs);
		}
		return b;
	}

	public List<User> QueryAll() {
		PreparedStatement ps = null;
		ps = dbUtil.prepareStatement("select id , name from login ");
		ResultSet rs = null;
		List<User> list = new ArrayList<User>();
		;
		try {
			rs = ps.executeQuery();
			while (rs.next()) {
				User user = new User();
				user.setId(rs.getInt("id"));
				user.setUserName(rs.getString("name"));
				list.add(user);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			dbUtil.close(ps);
			dbUtil.close(rs);
		}
		return list;
	}

	public void deleteById(int id) {
		PreparedStatement ps = null;
		ps = dbUtil.prepareStatement("delete from login where id = ?");
		try {
			ps.setInt(1, id);
			ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			dbUtil.close(ps);
		}
	}
	
	public void insert(String name,String password){
		PreparedStatement ps = null;
		ps = dbUtil.prepareStatement("insert into login(id,name,password) values(null,?,?)");
		try {
			ps.setString(1,name);
			ps.setString(2, password);
			ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			dbUtil.close(ps);
		}
	}
	
	public int update(String userName,String oldPwd,String newPwd){
		PreparedStatement ps = dbUtil.prepareStatement("update login set password=? where name=? and password=? ");
		try {
			ps.setString(1, newPwd);
			ps.setString(2, userName);
			ps.setString(3, oldPwd);
			
			
			return ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			dbUtil.close(ps);
		}
		return 0;
	}
}
